// @ts-nocheck

import {getSnapshot, loadSnapshot, exportToBlob} from "tldraw";

export const FocusAnyEditor = {
    run: (func: string, success: any, error: any, data: any, silence: boolean) => {
        try {
            if (!silence) {
                console.log('FocusAnyEditor.run', func, {success, error, data});
            }
            if (!FocusAnyEditor[func]) {
                setTimeout(() => {
                    FocusAnyEditor.run(func, success, error, data);
                }, 100)
                return;
            }
            FocusAnyEditor[func](success, error, data);
        } catch (e) {
            error && error(`RunError: ${e}`);
        }
    },
    fireChangeWithoutData: () => {
        if (!FocusAnyEditor.getContent) {
            return;
        }
        FocusAnyEditor.getContent((data: any) => {
            FocusAnyEditor.fireChange(data);
        })
    },
    fireChange: (data: any) => {
        window.parent.postMessage({
            type: 'ContentChange',
            data: data
        }, '*');
    },
    editorInit: null as any,
    getContent: null as any,
    setContent: null as any,
    export: null as any,
}

window.editorInit = (success, error) => {
    FocusAnyEditor.run('editorInit', success, error);
};
window.editorGetContent = (success, error) => {
    FocusAnyEditor.run('getContent', success, error);
};
window.editorSetContent = (success, error, content) => {
    FocusAnyEditor.run('setContent', success, error, content);
};
window.editorExport = (success, error, type) => {
    FocusAnyEditor.run('export', success, error, type);
}

export const useFocusAnyEditor = (data: {
    editor: any,
}) => {
    FocusAnyEditor.editorInit = (success: any, error: any) => {
        success && success();
    };
    FocusAnyEditor.setContent = (success: any, error: any, content: any) => {
        if (null === content) {
            content = JSON.parse(`{"document":{"store":{"document:document":{"gridSize":10,"name":"","meta":{},"id":"document:document","typeName":"document"},"page:page":{"meta":{},"id":"page:page","name":"Page 1","index":"a1","typeName":"page"}},"schema":{"schemaVersion":2,"sequences":{"com.tldraw.store":4,"com.tldraw.asset":1,"com.tldraw.camera":1,"com.tldraw.document":2,"com.tldraw.instance":25,"com.tldraw.instance_page_state":5,"com.tldraw.page":1,"com.tldraw.instance_presence":5,"com.tldraw.pointer":1,"com.tldraw.shape":4,"com.tldraw.asset.bookmark":2,"com.tldraw.asset.image":5,"com.tldraw.asset.video":5,"com.tldraw.shape.group":0,"com.tldraw.shape.text":2,"com.tldraw.shape.bookmark":2,"com.tldraw.shape.draw":2,"com.tldraw.shape.geo":9,"com.tldraw.shape.note":8,"com.tldraw.shape.line":5,"com.tldraw.shape.frame":0,"com.tldraw.shape.arrow":5,"com.tldraw.shape.highlight":1,"com.tldraw.shape.embed":4,"com.tldraw.shape.image":4,"com.tldraw.shape.video":2,"com.tldraw.binding.arrow":0}}},"session":{"version":0,"currentPageId":"page:page","exportBackground":true,"isFocusMode":false,"isDebugMode":false,"isToolLocked":false,"isGridMode":false,"pageStates":[{"pageId":"page:page","camera":{"x":0,"y":0,"z":1},"selectedShapeIds":[],"focusedGroupId":null}]}}`)
            loadSnapshot(data.editor.store, content)
        } else {
            content = JSON.parse(content)
            loadSnapshot(data.editor.store, content)
        }
        success && success();
    };
    FocusAnyEditor.getContent = (success: any, error: any) => {
        const {document, session} = getSnapshot(data.editor.store)
        const content = JSON.stringify({document, session})
        success && success(content);
    };
    FocusAnyEditor.export = (success: any, error: any, type: any) => {
        type = type || 'svg'
        console.log('export', type, data)
        const shapeIds = data.editor.getCurrentPageShapeIds()
        console.log('export', {shapeIds, type, data})
        if (shapeIds.size === 0) {
            error && error('No shapes to export')
            return
        }
        console.log('export.exportToBlob', {shapeIds, type, data})
        exportToBlob({
            editor: data.editor,
            ids: [...shapeIds],
            format: type,
            opts: {background: false},
        }).then((blob) => {
            console.log('export.exportToBlob.success', {shapeIds, type, data, blob})
            success && success(blob)
        }).catch((e) => {
            console.log('error', e)
            error && error(e)
        })
    }
    data.editor.store.listen((update: any) => {
        const {document, session} = getSnapshot(data.editor.store)
        const content = JSON.stringify({document, session})
        FocusAnyEditor.fireChange(content)
    }, {scope: 'document', source: 'user'});
}

